package com.anji.plus.gaea.job.executor.config;

import com.anji.plus.gaea.job.executor.service.XxlJobExecutor;
import com.anji.plus.gaea.job.executor.thread.ExecutorRegistryThread;
import com.anji.plus.gaea.job.executor.thread.JobLogFileCleanThread;
import com.anji.plus.gaea.job.executor.thread.TriggerCallbackThread;
import com.anji.plus.gaea.job.executor.util.XxlJobFileAppender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.SmartInitializingSingleton;

/**
 * @desc 执行器装配类
 * @author 木子李*de
 * @date 2023-05-12 15:25:35.961
 **/
public class ExecutorConfiguration extends XxlJobExecutor implements InitializingBean, SmartInitializingSingleton, DisposableBean {

    private static final Logger logger = LoggerFactory.getLogger(ExecutorConfiguration.class);

    // 单例
    private static ExecutorConfiguration instance = null;
    public static ExecutorConfiguration getInstance() {
        return instance;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.instance = this;

        // 初始化注册线程的变量
        ExecutorRegistryThread.getInstance().setApplicationContext(applicationContext);
        ExecutorRegistryThread.getInstance().setExecutorProperties(executorProperties);

    }

    @Override
    public void afterSingletonsInstantiated() {
        registJobHandler();

        // 初始化日志目录
        XxlJobFileAppender.initLogPath(getExecutorProperties().getLogHome());

        // 初始化调用trigger的客户端,负责注册\取消注册\回调等
        initTriggerClientList(executorProperties);

        // 清除过期日志线程
        JobLogFileCleanThread.getInstance().start(executorProperties.getLogMaxDays());

        // 初始化调度回调线程
        TriggerCallbackThread.getInstance().start();

        // 初始化注册线程
        ExecutorRegistryThread.getInstance().start();

        logger.info("初始化 gaea-job 执行器完成");
    }

    @Override
    public void destroy() throws Exception {

        destroyJobThread();

        ExecutorRegistryThread.getInstance().toStop();

        TriggerCallbackThread.getInstance().toStop();

        JobLogFileCleanThread.getInstance().toStop();
    }
}
